import localForage from 'localforage';

const localForageKey = '9c196820e56801f1';

export default {
  getCarts() {
    return localForage.getItem(localForageKey);
  },
  addCart(id, amount) {
    localForage.getItem(localForageKey).then(function(carts) {
      if (carts === null) {
        console.log('ok');
        carts = {};
        carts[id] = { amount: 1 };
      } else if (typeof (carts[id]) === 'undefined') {
        carts[id] = {};
        carts[id]['amount'] = 1;
      } else {
        carts[id]['amount'] += 1;
      }
      localForage.setItem(localForageKey, carts);
    });
  },
  deleteCart(ids) {
    localForage.getItem(localForageKey).then(function(carts) {
      if (carts === null) {
        return null;
      }

      localForage.removeItem(localForageKey);

      var tCarts = {};
      for (var i in carts) {
        if (Object.keys(ids).indexOf(i) === -1) {
          tCarts[i] = carts[i];
        }
      }

      localForage.setItem(localForageKey, tCarts);
    });
  }
};
